/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import models.Files;
import models.Lesson;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Achie
 */
public class FileDao {

    private final Session session;

    public FileDao(Session session) {
        this.session = session;
    }

    public List<Files> findAll() {
        Transaction tx = session.beginTransaction();
        List<Files> list = session.createQuery("from Files as c ORDER BY c.name ASC").list();
        tx.commit();
        return list;
    }

    public List<Files> findAllByCategory(long id) {
        Transaction tx = session.beginTransaction();
        List<Files> list = session.createQuery("from Files where category_id= :id").setParameter("id", id).list();
        tx.commit();
        return list;
    }

    public boolean save(Files files) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(files);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean update(Files files) {
        try {
            Transaction tx = session.beginTransaction();
            session.update(files);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public Files get(long id) {
        return (Files) session.get(Files.class, id);
    }

    public void delete(Files files) {
        Transaction tx = session.beginTransaction();
        session.delete(files);
        tx.commit();
    }

    //get all file objects from a lesson
    public List<Files> findAllFilesInLesson(long id) {
        Transaction tx = session.beginTransaction();
        List<Files> list = session.createQuery("from Files where lesson_lesson_id= :id").setParameter("id", id).list();
        tx.commit();
        return list;
    }

    //get all file objects from a course
    public List<Files> findAllFilesInCourse(long courseid) {
        Transaction tx = session.beginTransaction();
        List<Files> list = session.createQuery("from Files where lesson_lesson_id IN (select li.id from Lesson li where li.course.id= :id)").setParameter("id", courseid).list();
        tx.commit();
        return list;
    }
}
